package org.openfidias.jdbase.db;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;

/**
 *
 * @author atila
 */
public class DbManager {

   private static final String dir = "data/";

   public static File getTable(String tableName) throws IOException {
      File data = new File(dir);
      if (!data.exists()) {
         data.mkdir();
      }

      File table = new File(dir.concat(tableName));
      if (!table.exists()) {
         table.createNewFile();
      }
      return table;
   }

   /**
    * Salva o ponteiro para a tabela para posterior uso do espaço deixado pelo registro deletado.
    * @param table
    * @param pointer
    * @throws IOException
    * @throws Exception
    */
   public static void logicalDelete(String table, long pointer) throws IOException, Exception {
      try {
         File f = getTable(table);
         PrintWriter writer = new PrintWriter(new FileOutputStream(f, true));
         String line = "0:".concat(String.valueOf(pointer));
         writer.println(line);
         writer.close();
      } catch (IOException e) {
         throw new IOException(e);
      } catch (Exception e) {
         throw new Exception(e);
      }
   }

   public static Long getPointer(String table) throws IOException {
      Long curPointer = null;
      boolean hasDeleted = false;
      boolean sentinel = false;
      File f = getTable(table);
      RandomAccessFile file = new RandomAccessFile(f, "rw");
      long pointer = file.getFilePointer();
      String line = file.readLine();
      while (line != null) {
         String[] array = line.split(":");

         if ("0".equals(array[0])) {
            if (!sentinel) {
               curPointer = Long.parseLong(array[1]);
               file.seek(pointer);
               file.write("1".getBytes());
               sentinel = true;
            } else { // verifica se ainda existem ponteiros a serem deletados da tabela.
               hasDeleted = true;
            }
         }

         pointer = file.getFilePointer();
         line = file.readLine();
      }
      file.close();

      // se não houver mais arquivos a serem deletados, deleta o arquivo.
      if (!hasDeleted) {
         f.delete();
      }
      
      return curPointer;
   }
}
